package com.dotstone.chipism.activity;

import com.dotstone.chipism.R;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.NetworkUtil;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.WifiAdmin;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PairWlanActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mTitleTv;
	private TextView mWlanTv;
	// private LinearLayout mSelectL;
	private EditText mPwdEd;
	private Button mNextB;
	private TextView mStatusBar;
	private WifiAdmin mWifiAdmin;
	private boolean stop;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private boolean wifiEnable = false;
	private SVProgressHUD mSVProgressHUD;
	private IntentFilter filter;
	private NetworkConnectChangedReceiver receiver;
	public static PairWlanActivity pairWlanActivity;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.nextstep1:
			if (wifiEnable) {
				String ssid = mWlanTv.getText().toString();
				String password = mPwdEd.getText().toString();
				boolean nopwd;
				if (password.length() == 0) {
					nopwd = true;
				} else {
					nopwd = false;
				}
				Intent intent = new Intent(PairWlanActivity.this,
						PairWlanActivity1.class);
				intent.putExtra("ssid", ssid);
				intent.putExtra("password", password);
				intent.putExtra("nopwd", nopwd);
				startActivity(intent);
			} else {
				mNormalDialog = new NormalDialog(PairWlanActivity.this);
				mNormalDialog.content("您尚未打开WIFI，是否需要打开？")
						.style(NormalDialog.STYLE_TWO)//
						.titleTextSize(18)//
						.showAnim(bas_in)//
						.dismissAnim(bas_out)//
						.show();
				mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
					}
				}, new OnBtnClickL() {
					@Override
					public void onBtnClick() {
						mNormalDialog.dismiss();
						mWifiAdmin.openWifi();
						mSVProgressHUD = new SVProgressHUD(
								PairWlanActivity.this);
						mSVProgressHUD.showWithStatus("正在打开WIFI...");
					}

				});
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		stop = false;
		check5G();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		stop = true;
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_pair_wlan;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (wifiEnable) {
					mWlanTv.setText(mWifiAdmin.getWifiConnectedSsid());
				} else {

				}
				break;
			case 2:
				mWlanTv.setVisibility(View.VISIBLE);
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		pairWlanActivity = this;
		mBackL = $(R.id.back_layout);
		mTitleTv = $(R.id.title_tv);
		mTitleTv.setVisibility(View.GONE);
		mWlanTv = $(R.id.wlan_tv);
		mPwdEd = $(R.id.pwd_ed);
//		String digits = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!\"#$%&'()*+,-./:;<=>?@[\\]^-{}";
//		mPwdEd.setKeyListener(DigitsKeyListener.getInstance(digits));
		mNextB = $(R.id.nextstep1);
		mStatusBar = $(R.id.tv_statusBar_mian);
		boolVersion();
		mBackL.setOnClickListener(this);
		mNextB.setOnClickListener(this);
		mNormalDialog = new NormalDialog(PairWlanActivity.this);
		mWifiAdmin = new WifiAdmin(PairWlanActivity.this);
		mSVProgressHUD = new SVProgressHUD(PairWlanActivity.this);
		filter = new IntentFilter();
		receiver = new NetworkConnectChangedReceiver();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(receiver, filter);
		checkWifi();
		initData();
	}
	
	private void check5G(){
		if(mWifiAdmin!=null){
			
		}else{
			mWifiAdmin = new WifiAdmin(getApplicationContext());
		}
		mWifiAdmin.startScan();
		if(mWifiAdmin.is5G(mWifiAdmin.getWifiConnectedSsid())){
			mNormalDialog = new NormalDialog(PairWlanActivity.this);
			mNormalDialog.content("您当前所连WIFI是5G，不支持在5G的WIFI下配网，请切换至2.4G的WIFI。")
					.style(NormalDialog.STYLE_TWO)//
					.titleTextSize(18)//
					.showAnim(bas_in)//
					.dismissAnim(bas_out)//
					.show();
			mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
				@Override
				public void onBtnClick() {
					mNormalDialog.dismiss();
					ToastShow.Show(getApplicationContext(), "取消配置");
					finish();
				}
			}, new OnBtnClickL() {
				@Override
				public void onBtnClick() {
					mNormalDialog.dismiss();
					Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");  
					startActivity(wifiSettingsIntent); 
				}
			});
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		// unregisterReceiver(receiver);
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void initData() {
		// TODO Auto-generated method stub
		// 传入wifi列表 加载至WIFI选择框
		// mWifiAdmin = new WifiAdmin(PairWlanActivity.this);
		String ssid = mWifiAdmin.getWifiConnectedSsid();
		mWlanTv.setText(ssid);
	}

	private void checkWifi() {
		mWifiAdmin = new WifiAdmin(PairWlanActivity.this);
		if (NetworkUtil.getWifiConnected(getApplicationContext())) {
			// 已经打开 不管他
			mWlanTv.setVisibility(View.VISIBLE);
			wifiEnable = true;
		} else {
			// 询问是否需要打开Wifi
			wifiEnable = false;
			mNormalDialog = new NormalDialog(PairWlanActivity.this);
			mNormalDialog.content("您尚未打开WIFI，是否需要打开？")
					.style(NormalDialog.STYLE_TWO)//
					.titleTextSize(18)//
					.showAnim(bas_in)//
					.dismissAnim(bas_out)//
					.show();
			mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
				@Override
				public void onBtnClick() {
					mNormalDialog.dismiss();
				}
			}, new OnBtnClickL() {
				@Override
				public void onBtnClick() {
					mNormalDialog.dismiss();
					mWifiAdmin.openWifi();
					mSVProgressHUD = new SVProgressHUD(PairWlanActivity.this);
					mSVProgressHUD.showWithStatus("正在打开WIFI...");
				}

			});
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (true) {

					try {
						if (!stop) {
							Message msg = Message.obtain();
							msg.what = 1;
							mHandler.sendMessage(msg);
						}
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
		}).start();
	}

	class NetworkConnectChangedReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (WifiManager.WIFI_STATE_CHANGED_ACTION
					.equals(intent.getAction())) {// 这个监听wifi的打开与关闭，与wifi的连接无关
				int wifiState = intent.getIntExtra(
						WifiManager.EXTRA_WIFI_STATE, 0);
				Log.e("Tag", "wifiState" + wifiState);
				switch (wifiState) {
				case WifiManager.WIFI_STATE_DISABLED:
					Log.i("Tag", "wifi关闭");
					wifiEnable = false;
					break;
				case WifiManager.WIFI_STATE_DISABLING:
					break;
				case WifiManager.WIFI_STATE_ENABLING:
					Log.i("Tag", "正在打开wifi");
					break;
				case WifiManager.WIFI_STATE_ENABLED:
					Log.i("Tag", "wifi已经打开");
					// mNextBtn.setVisibility(View.VISIBLE);
					if (mSVProgressHUD.isShowing()) {
						ToastShow.Show(getApplicationContext(),
								getString(R.string.wifi_connected));
						mSVProgressHUD.dismiss();
					}
					wifiEnable = true;
					break;
				}
			}
			// 这个监听wifi的连接状态即是否连上了一个有效无线路由，当上边广播的状态是WifiManager.WIFI_STATE_DISABLING，和WIFI_STATE_DISABLED的时候，根本不会接到这个广播。
			// 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播，当然刚打开wifi肯定还没有连接到有效的无线
			if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent
					.getAction())) {
				Parcelable parcelableExtra = intent
						.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				if (null != parcelableExtra) {
					NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
					State state = networkInfo.getState();
					boolean isConnected = state == State.CONNECTED;// 当然，这边可以更精确的确定状态
					Log.e("Tag", "isConnected" + isConnected);
					if (isConnected) {
					} else {
						mHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Message msg = Message.obtain();
								msg.what = 2;
								mHandler.sendMessage(msg);
							}
						}, 6 * 1000);
					}
				}
			}

		}
	}

}
